package com.lksoft.bz.tool;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JToggleButton;

import com.lksoft.bz.Bz;

/**
 * Tool interface
 * 
 * @author lake
 *
 */
public abstract class Tool implements MouseListener, MouseMotionListener{
	
	/** Icon */
	private String iconPath;
	/** Resource name */
	private String resourceName;
	
	/** Button */
	JToggleButton button;
	
	/** The program */
	protected Bz bz;
	
	/**
	 * Build with an icon and resourceName
	 * @param icon
	 * @param tooltipText
	 * @throws IOException 
	 */
	public Tool(Bz bz, String iconPath, String resourceName) throws IOException{
		this.bz = bz;
		this.iconPath = iconPath;
		this.resourceName = resourceName;
		
		makeButton(bz);
	}
	
	/**
	 * 現在のLocaleでテキスを更新する
	 */
	public void updateText(){
		button.setToolTipText(Bz.getUIString(resourceName+".tooltip"));
	}
	
	/**
	 * ツールボタンを作成
	 * @param panel
	 * @return
	 * @throws IOException 
	 */
	void makeButton(final Bz bz) throws IOException{		
		button = new JToggleButton("");
		button.setIcon(new ImageIcon(
				ImageIO.read(Bz.class.getResourceAsStream(iconPath)).getScaledInstance(34, 34, Image.SCALE_SMOOTH)
				));
		
		
		// Change mouse listeners
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if( bz.getStitchPanel().getMouseListeners().length > 0 ){
					bz.getStitchPanel().removeMouseListener(bz.getStitchPanel().getMouseListeners()[0]);
				}
				if( bz.getStitchPanel().getMouseMotionListeners().length > 0 ){
					bz.getStitchPanel().removeMouseMotionListener(bz.getStitchPanel().getMouseMotionListeners()[0]);
				}
				bz.getStitchPanel().addMouseListener(Tool.this);
				bz.getStitchPanel().addMouseMotionListener(Tool.this);
			}
		});
	}
	
	/**
	 * @return The button
	 */
	public JToggleButton getButton(){
		return button;
	}
}
